﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace 深入浅出WPF_Chapter8路由事件
{
    /// <summary>
    /// Interaction logic for Sample5.xaml
    /// </summary>
    public partial class Sample5 : Window
    {
        public Sample5()
        {
            InitializeComponent();

            //为外层Grid添加路由事件侦听器
            Student2.AddNameChangedHandler(this.gridMain, new RoutedEventHandler(this.StudentNameChangedHandler));
        }

        //Grid捕捉到NameChangedEvent后的处理器
        private void StudentNameChangedHandler(object sender, RoutedEventArgs e)
        {
            MessageBox.Show((e.OriginalSource as Student2).Id.ToString());
            //MessageBox.Show((e.OriginalSource as Student).Name.ToString());   //Tom
            MessageBox.Show((e.Source as FrameworkElement).Name);
        }

        //Click 事件处理器
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student2 stu = new Student2() { Id = 101, Name = "Tim" };
            stu.Name = "Tom";

            //准备事件消息并发送路由事件
            RoutedEventArgs arg = new RoutedEventArgs(Student2.NameChangedEvent, stu);
            this.button1.RaiseEvent(arg);
        }
    }

    public class Student2
    {
        //声明并定义路由事件
        public static readonly RoutedEvent NameChangedEvent = EventManager.RegisterRoutedEvent("NameChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Student));

        //为界面元素添加路由事件侦听
        public static void AddNameChangedHandler(DependencyObject d,RoutedEventHandler h)
        {
            UIElement e = d as UIElement;
            if (e != null)
            {
                e.AddHandler(Student2.NameChangedEvent, h);
            }
        }

        //移除侦听
        public static void RemoveNameChangedHandler(DependencyObject d,RoutedEventHandler h)
        {
            UIElement e = d as UIElement;
            if (e != null)
            {
                e.RemoveHandler(Student2.NameChangedEvent, h);
            }
        }

        public int Id { get; set; }
        public string Name { get; set; }
    }
}
